package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.WeeklyTemplate;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 05月 24日
 * Time: 下午12:19
 *
 * @QQ : 1234567890
 * **********************************
 */
public class WeeklyTemplateEditActivity extends MyBaseActivity implements View.OnClickListener{

    @FindViewById(id = R.id.weekly_date_lv)
    private ListView mListView;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.weekly_edit_tv)
    private EditText mEtTitle;
    @FindViewById(id = R.id.rl_weekly_title)
    private RelativeLayout mLayoutTitle;



    private Dialog mWaitDialog;
    private WeeklyEditMouldAdapter mAdapter;
    private ArrayList<String> mDatas = new ArrayList<String>();
    private ArrayList<String> mEditDatas = new ArrayList<String>();
    private WeeklyTemplate mWeeklyTemplate = new WeeklyTemplate();

    private String mGroupId;
    private String mTitle;
    private int flag; // 1、创建  2、修改


    private static final int WEEKLY_TEMPLATE = 10001;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WEEKLY_TEMPLATE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        setResult(RESULT_OK);
                        finish();

                    }else{
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.weekly_date_layout);
    }

    @Override
    public void initListener() {
        mTvRight.setOnClickListener(this);
        mLayoutBack.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mTvRight.setText("保存");
        mLayoutTitle.setVisibility(View.VISIBLE);
        Intent passIntent = getIntent();
        String action = passIntent.getAction();
        if ("create_template".equals(action)){
            mTvTitle.setText("周报模板");
            flag = 1;
            mGroupId = passIntent.getStringExtra("group_id");
        }else{
            mTvTitle.setText("编辑模板");
            flag = 2;
            mWeeklyTemplate = (WeeklyTemplate) passIntent.getSerializableExtra("template");
            mTitle = mWeeklyTemplate.getTemplate_name();
            mDatas = mWeeklyTemplate.getFields();
            mGroupId = mWeeklyTemplate.getGroup_id();
            if (!StringUtil.isEmpty(mTitle)){
                mEtTitle.setText(mTitle);
            }
        }
        if (mDatas.size() == 0) {
            mDatas.add("");
            mDatas.add("");
            mDatas.add("");
        }
        mAdapter = new WeeklyEditMouldAdapter();
        mListView.setAdapter(mAdapter);

    }

    /**
     * 获取内容（不考虑条目内容为空）
     *
     * @return
     */
    public void getMouldData() {
        mDatas.clear();
        for (int i = 0; i < mListView.getChildCount(); i++) {
            LinearLayout layout = (LinearLayout) mListView.getChildAt(i);// 获得子item的layout
            EditText et = (EditText) layout.getChildAt(0).findViewById(R.id.vote_item_et_content);// 从layout中获得控件,根据其id
            // EditText et = (EditText) layout.getChildAt(1)//或者根据位置,在这我假设TextView在前，EditText在后
            mDatas.add(et.getText().toString().trim());
        }
    }
    /**
     * 保存时获取内容（条目内容为空的去掉）
     *
     * @return
     */
    public void getEditMouldData() {
        mEditDatas.clear();
        for (int i = 0; i < mListView.getChildCount(); i++) {
            LinearLayout layout = (LinearLayout) mListView.getChildAt(i);// 获得子item的layout
            EditText et = (EditText) layout.getChildAt(0).findViewById(R.id.vote_item_et_content);// 从layout中获得控件,根据其id
            // EditText et = (EditText) layout.getChildAt(1)//或者根据位置,在这我假设TextView在前，EditText在后
            String item = et.getText().toString().trim();
            if (!StringUtil.isEmpty(item)){
                mEditDatas.add(item);
            }
        }
    }

    public void onUpdateAdd() {
        if (mDatas.size() == 5) {
            Toast.makeText(this, "最多5个选项", Toast.LENGTH_SHORT).show();
        } else {
            getMouldData();
            mDatas.add("");
            mAdapter.notifyDataSetChanged();
        }
    }

    public void onUpdateRemove(int i) {
        getMouldData();
        mDatas.remove(i);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.title_tv_right:
                checkContent();
                break;
        }
    }

    /**
     * 检查字段是否符合标准
     */
    private void checkContent(){
        mTitle = mEtTitle.getText().toString().trim();
        if (StringUtil.isEmpty(mTitle)){
            showShortToast("模板名称不能为空");
            return;
        }
        getEditMouldData();
        if (mEditDatas.size() == 0){
            showShortToast("至少填写一个标题");
            return;
        }
        editTemplate();
    }

    /**
     * 创建新的模板
     */
    private void editTemplate() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TEMPLATE_NAME, mTitle));
        if (flag == 2){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TEMPLATE_ID, mWeeklyTemplate.get_id()));
            nvps.add(new BasicNameValuePair("is_default", mWeeklyTemplate.getIs_default() + ""));
        }

        JSONArray array = new JSONArray();
        for (int i = 0;i<mEditDatas.size();i++){
            try {
                JSONObject item = new JSONObject();
                item.put("order",i+1);
                item.put("field",mEditDatas.get(i));
                array.put(item);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_FIELDS, array.toString()));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(WEEKLY_TEMPLATE));
        if (flag == 1){
            message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_ADD;
        }else{
            message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_UPDATE;
        }
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
        httpReqDlgShow();
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    class WeeklyEditMouldAdapter extends BaseAdapter {

        String[] hints = {"例 本周计划","例 下周计划","例 需求帮助","",""};

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return mDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(mActivity).inflate(R.layout.vote_item_layout, null);
            ImageView image = (ImageView) convertView.findViewById(R.id.vote_item_iv);
            TextView text = (TextView) convertView.findViewById(R.id.vote_item_tv_title);
            EditText editText = (EditText) convertView.findViewById(R.id.vote_item_et_content);
            if (position == mDatas.size() - 1) {
                image.setBackgroundResource(R.drawable.vote_add_seletor);
                image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ((WeeklyTemplateEditActivity) mActivity).onUpdateAdd();
                    }
                });
            } else {
                image.setBackgroundResource(R.drawable.vote_remove_seletor);
                image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ((WeeklyTemplateEditActivity) mActivity).onUpdateRemove(position);
                    }
                });
            }
            text.setText("字段标题：");
            String title = mDatas.get(position);
            if (StringUtil.isEmpty(title)) {
                editText.setHint(hints[position]);
            } else {
                editText.setText(mDatas.get(position));
            }
            editText.addTextChangedListener(new TextWatcher() {
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void afterTextChanged(Editable s) {
                    // TODO 修改数据
                    mDatas.set(position, s.toString());
                }
            });
            return convertView;
        }
    }

}
